package com.sline.smis.jdbc.template.handler;

import com.sline.smis.jdbc.domain.Column;
import com.sline.smis.jdbc.template.ResultSetHandler;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.sql.ResultSet;

public class BeanResultSetHandler<T> implements ResultSetHandler {

    private Class<T> classType;

    public BeanResultSetHandler(Class<T> classType) {
        this.classType = classType;
    }

    @Override
    public Object handle(ResultSet resultSet) throws Exception {
        if (resultSet.next()) {

            T obj = this.classType.newInstance();

            BeanInfo beanInfo = Introspector.getBeanInfo(this.classType, Object.class);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor: propertyDescriptors){
                String key = propertyDescriptor.getName();
                Field field = this.classType.getDeclaredField(key);
                if (field.isAnnotationPresent(Column.class)) {
                    Column column = field.getAnnotation(Column.class);

                    key = column.value();
                }

                Object value = resultSet.getObject(key);
                propertyDescriptor.getWriteMethod().invoke(obj, value);
            }

            return obj;
        }
        return null;
    }
}
